/**
 * 上传相关Mock数据
 */

import { generateId, randomNumber, randomChoice } from '../utils'

// 模拟上传文件数据
const mockUploadedFiles = []

// 支持的文件类型
const SUPPORTED_FILE_TYPES = {
  image: ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'],
  document: ['pdf', 'doc', 'docx', 'txt', 'md'],
  spreadsheet: ['xls', 'xlsx', 'csv'],
  archive: ['zip', 'rar', '7z'],
  audio: ['mp3', 'wav', 'aac', 'm4a'],
  video: ['mp4', 'avi', 'mov', 'wmv']
}

// 文件大小限制（字节）
const FILE_SIZE_LIMITS = {
  image: 10 * 1024 * 1024, // 10MB
  document: 50 * 1024 * 1024, // 50MB
  spreadsheet: 20 * 1024 * 1024, // 20MB
  archive: 100 * 1024 * 1024, // 100MB
  audio: 50 * 1024 * 1024, // 50MB
  video: 200 * 1024 * 1024 // 200MB
}

// 获取文件类型
function getFileType(filename) {
  const extension = filename.split('.').pop().toLowerCase()
  
  for (const [type, extensions] of Object.entries(SUPPORTED_FILE_TYPES)) {
    if (extensions.includes(extension)) {
      return type
    }
  }
  
  return 'unknown'
}

// 验证文件
function validateFile(file) {
  const errors = []
  
  // 检查文件名
  if (!file.name || file.name.trim() === '') {
    errors.push('文件名不能为空')
  }
  
  // 检查文件大小
  if (!file.size || file.size <= 0) {
    errors.push('文件大小无效')
  }
  
  // 检查文件类型
  const fileType = getFileType(file.name)
  if (fileType === 'unknown') {
    errors.push('不支持的文件类型')
  } else {
    // 检查文件大小限制
    const sizeLimit = FILE_SIZE_LIMITS[fileType]
    if (file.size > sizeLimit) {
      errors.push(`文件大小超过限制（最大 ${Math.round(sizeLimit / 1024 / 1024)}MB）`)
    }
  }
  
  return errors
}

// 生成文件URL
function generateFileUrl(fileId, filename) {
  const extension = filename.split('.').pop()
  return `https://cdn.tictac.app/uploads/${fileId}.${extension}`
}

// 生成缩略图URL
function generateThumbnailUrl(fileId, filename) {
  const fileType = getFileType(filename)
  if (fileType === 'image') {
    return `https://cdn.tictac.app/thumbnails/${fileId}_thumb.jpg`
  }
  return null
}

export default {
  // 上传文件
  'POST /upload': async (data) => {
    const { file, category = 'general', description = '' } = data
    
    if (!file) {
      throw new Error(JSON.stringify({ code: 1001, message: '请选择要上传的文件' }))
    }
    
    // 验证文件
    const validationErrors = validateFile(file)
    if (validationErrors.length > 0) {
      throw new Error(JSON.stringify({ 
        code: 1001, 
        message: '文件验证失败', 
        errors: validationErrors 
      }))
    }
    
    // 模拟上传过程
    const fileId = generateId()
    const fileType = getFileType(file.name)
    
    const uploadedFile = {
      id: fileId,
      filename: file.name,
      originalName: file.name,
      size: file.size,
      type: fileType,
      mimeType: file.type || 'application/octet-stream',
      category,
      description,
      url: generateFileUrl(fileId, file.name),
      thumbnailUrl: generateThumbnailUrl(fileId, file.name),
      uploadedAt: new Date().toISOString(),
      uploadedBy: 'user_001',
      downloads: 0,
      status: 'completed'
    }
    
    mockUploadedFiles.unshift(uploadedFile)
    
    return uploadedFile
  },
  
  // 批量上传文件
  'POST /upload/batch': async (data) => {
    const { files, category = 'general', description = '' } = data
    
    if (!files || !Array.isArray(files) || files.length === 0) {
      throw new Error(JSON.stringify({ code: 1001, message: '请选择要上传的文件' }))
    }
    
    if (files.length > 10) {
      throw new Error(JSON.stringify({ code: 1001, message: '单次最多上传10个文件' }))
    }
    
    const results = []
    
    for (const file of files) {
      try {
        // 验证文件
        const validationErrors = validateFile(file)
        if (validationErrors.length > 0) {
          results.push({
            filename: file.name,
            success: false,
            errors: validationErrors
          })
          continue
        }
        
        // 模拟上传
        const fileId = generateId()
        const fileType = getFileType(file.name)
        
        const uploadedFile = {
          id: fileId,
          filename: file.name,
          originalName: file.name,
          size: file.size,
          type: fileType,
          mimeType: file.type || 'application/octet-stream',
          category,
          description,
          url: generateFileUrl(fileId, file.name),
          thumbnailUrl: generateThumbnailUrl(fileId, file.name),
          uploadedAt: new Date().toISOString(),
          uploadedBy: 'user_001',
          downloads: 0,
          status: 'completed'
        }
        
        mockUploadedFiles.unshift(uploadedFile)
        
        results.push({
          filename: file.name,
          success: true,
          file: uploadedFile
        })
        
      } catch (error) {
        results.push({
          filename: file.name,
          success: false,
          errors: [error.message]
        })
      }
    }
    
    return {
      total: files.length,
      successful: results.filter(r => r.success).length,
      failed: results.filter(r => !r.success).length,
      results
    }
  },
  
  // 获取上传文件列表
  'GET /upload/files': async (params = {}) => {
    const { 
      page = 1, 
      pageSize = 20, 
      type, 
      category, 
      search,
      sortBy = 'uploadedAt',
      sortOrder = 'desc'
    } = params
    
    let filteredFiles = [...mockUploadedFiles]
    
    // 按类型筛选
    if (type) {
      filteredFiles = filteredFiles.filter(file => file.type === type)
    }
    
    // 按分类筛选
    if (category) {
      filteredFiles = filteredFiles.filter(file => file.category === category)
    }
    
    // 搜索
    if (search) {
      const searchLower = search.toLowerCase()
      filteredFiles = filteredFiles.filter(file => 
        file.filename.toLowerCase().includes(searchLower) ||
        file.description.toLowerCase().includes(searchLower)
      )
    }
    
    // 排序
    filteredFiles.sort((a, b) => {
      let aValue = a[sortBy]
      let bValue = b[sortBy]
      
      if (sortBy === 'uploadedAt') {
        aValue = new Date(aValue)
        bValue = new Date(bValue)
      }
      
      if (sortOrder === 'desc') {
        return bValue > aValue ? 1 : bValue < aValue ? -1 : 0
      } else {
        return aValue > bValue ? 1 : aValue < bValue ? -1 : 0
      }
    })
    
    // 分页
    const startIndex = (page - 1) * pageSize
    const endIndex = startIndex + pageSize
    const paginatedFiles = filteredFiles.slice(startIndex, endIndex)
    
    return {
      data: paginatedFiles,
      pagination: {
        page,
        pageSize,
        total: filteredFiles.length,
        totalPages: Math.ceil(filteredFiles.length / pageSize)
      }
    }
  },
  
  // 获取文件详情
  'GET /upload/files/:id': async (params, { pathParams }) => {
    const { id } = pathParams
    const file = mockUploadedFiles.find(file => file.id === id)
    
    if (!file) {
      throw new Error(JSON.stringify({ code: 1003, message: '文件不存在' }))
    }
    
    return file
  },
  
  // 更新文件信息
  'PUT /upload/files/:id': async (data, { pathParams }) => {
    const { id } = pathParams
    const fileIndex = mockUploadedFiles.findIndex(file => file.id === id)
    
    if (fileIndex === -1) {
      throw new Error(JSON.stringify({ code: 1003, message: '文件不存在' }))
    }
    
    const allowedFields = ['filename', 'category', 'description']
    const updates = {}
    
    allowedFields.forEach(field => {
      if (data[field] !== undefined) {
        updates[field] = data[field]
      }
    })
    
    // 如果更新了文件名，需要更新URL
    if (updates.filename) {
      const fileId = mockUploadedFiles[fileIndex].id
      updates.url = generateFileUrl(fileId, updates.filename)
      updates.thumbnailUrl = generateThumbnailUrl(fileId, updates.filename)
      updates.type = getFileType(updates.filename)
    }
    
    mockUploadedFiles[fileIndex] = {
      ...mockUploadedFiles[fileIndex],
      ...updates,
      updatedAt: new Date().toISOString()
    }
    
    return mockUploadedFiles[fileIndex]
  },
  
  // 删除文件
  'DELETE /upload/files/:id': async (data, { pathParams }) => {
    const { id } = pathParams
    const fileIndex = mockUploadedFiles.findIndex(file => file.id === id)
    
    if (fileIndex === -1) {
      throw new Error(JSON.stringify({ code: 1003, message: '文件不存在' }))
    }
    
    mockUploadedFiles.splice(fileIndex, 1)
    
    return { message: '文件删除成功' }
  },
  
  // 批量删除文件
  'POST /upload/files/batch-delete': async (data) => {
    const { ids } = data
    
    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      throw new Error(JSON.stringify({ code: 1001, message: '请选择要删除的文件' }))
    }
    
    const results = []
    
    for (const id of ids) {
      const fileIndex = mockUploadedFiles.findIndex(file => file.id === id)
      if (fileIndex !== -1) {
        const file = mockUploadedFiles[fileIndex]
        mockUploadedFiles.splice(fileIndex, 1)
        results.push({
          id,
          filename: file.filename,
          success: true
        })
      } else {
        results.push({
          id,
          success: false,
          error: '文件不存在'
        })
      }
    }
    
    return {
      total: ids.length,
      successful: results.filter(r => r.success).length,
      failed: results.filter(r => !r.success).length,
      results
    }
  },
  
  // 下载文件
  'GET /upload/files/:id/download': async (params, { pathParams }) => {
    const { id } = pathParams
    const file = mockUploadedFiles.find(file => file.id === id)
    
    if (!file) {
      throw new Error(JSON.stringify({ code: 1003, message: '文件不存在' }))
    }
    
    // 增加下载次数
    file.downloads += 1
    
    return {
      downloadUrl: file.url,
      filename: file.filename,
      size: file.size,
      expiresAt: new Date(Date.now() + 60 * 60 * 1000).toISOString() // 1小时后过期
    }
  },
  
  // 获取上传统计
  'GET /upload/stats': async (params = {}) => {
    const { period = 'month' } = params
    
    const now = new Date()
    let startDate
    
    switch (period) {
      case 'day':
        startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate())
        break
      case 'week':
        const weekStart = now.getDate() - now.getDay()
        startDate = new Date(now.getFullYear(), now.getMonth(), weekStart)
        break
      case 'month':
        startDate = new Date(now.getFullYear(), now.getMonth(), 1)
        break
      case 'year':
        startDate = new Date(now.getFullYear(), 0, 1)
        break
      default:
        startDate = new Date(now.getFullYear(), now.getMonth(), 1)
    }
    
    const periodFiles = mockUploadedFiles.filter(file => {
      return new Date(file.uploadedAt) >= startDate
    })
    
    // 按类型统计
    const typeStats = {}
    Object.keys(SUPPORTED_FILE_TYPES).forEach(type => {
      typeStats[type] = {
        count: 0,
        size: 0
      }
    })
    
    periodFiles.forEach(file => {
      if (typeStats[file.type]) {
        typeStats[file.type].count += 1
        typeStats[file.type].size += file.size
      }
    })
    
    // 按分类统计
    const categoryStats = {}
    periodFiles.forEach(file => {
      if (!categoryStats[file.category]) {
        categoryStats[file.category] = {
          count: 0,
          size: 0
        }
      }
      categoryStats[file.category].count += 1
      categoryStats[file.category].size += file.size
    })
    
    const totalSize = periodFiles.reduce((sum, file) => sum + file.size, 0)
    const totalDownloads = periodFiles.reduce((sum, file) => sum + file.downloads, 0)
    
    return {
      period,
      totalFiles: periodFiles.length,
      totalSize,
      totalDownloads,
      averageFileSize: periodFiles.length > 0 ? Math.round(totalSize / periodFiles.length) : 0,
      typeStats: Object.entries(typeStats).map(([type, stats]) => ({
        type,
        ...stats
      })),
      categoryStats: Object.entries(categoryStats).map(([category, stats]) => ({
        category,
        ...stats
      }))
    }
  },
  
  // 获取存储配额
  'GET /upload/quota': async () => {
    const totalUsed = mockUploadedFiles.reduce((sum, file) => sum + file.size, 0)
    const quota = 1024 * 1024 * 1024 * 5 // 5GB
    
    return {
      quota,
      used: totalUsed,
      available: quota - totalUsed,
      percentage: Math.round((totalUsed / quota) * 100),
      fileCount: mockUploadedFiles.length,
      maxFileSize: Math.max(...Object.values(FILE_SIZE_LIMITS)),
      supportedTypes: SUPPORTED_FILE_TYPES
    }
  },
  
  // 清理过期文件
  'POST /upload/cleanup': async (data) => {
    const { olderThan, dryRun = false } = data
    
    if (!olderThan) {
      throw new Error(JSON.stringify({ code: 1001, message: '请指定清理时间' }))
    }
    
    const cutoffDate = new Date(olderThan)
    const expiredFiles = mockUploadedFiles.filter(file => 
      new Date(file.uploadedAt) < cutoffDate
    )
    
    if (!dryRun) {
      // 实际删除文件
      expiredFiles.forEach(file => {
        const index = mockUploadedFiles.findIndex(f => f.id === file.id)
        if (index !== -1) {
          mockUploadedFiles.splice(index, 1)
        }
      })
    }
    
    const freedSpace = expiredFiles.reduce((sum, file) => sum + file.size, 0)
    
    return {
      message: dryRun ? '清理预览完成' : '清理完成',
      deletedFiles: expiredFiles.length,
      freedSpace,
      files: dryRun ? expiredFiles.map(file => ({
        id: file.id,
        filename: file.filename,
        size: file.size,
        uploadedAt: file.uploadedAt
      })) : undefined
    }
  }
}